package com.pennywise.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.sql.DataSource;
import java.io.File;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class FlywayConfig {

    private static final String BASE_DIR = System.getProperty("user.dir") + "/data";
    
    @Bean
    @DependsOn("directoryInitializer")
    public Flyway flyway(DataSource dataSource) {
        log.info("初始化Flyway配置");
        
        // 确保数据库目录存在
        String dbPath = BASE_DIR + "/db";
        File dbDir = new File(dbPath);
        if (!dbDir.exists()) {
            boolean created = dbDir.mkdirs();
            if (created) {
                log.info("创建数据库目录: {}", dbPath);
            } else {
                log.error("创建数据库目录失败: {}", dbPath);
                throw new RuntimeException("无法创建数据库目录");
            }
        }
        
        Flyway flyway = Flyway.configure()
                .dataSource(dataSource)
                .locations("classpath:db/migration")  // 迁移脚本位置
                .baselineOnMigrate(true)  // 在非空数据库时自动执行基准迁移
                .validateOnMigrate(true)  // 迁移时进行验证
                .load();
        
        log.info("开始执行数据库迁移");
        flyway.migrate();
        log.info("数据库迁移完成");
        
        return flyway;
    }
} 